package com.weyoung.admin.service.impl;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weyoung.admin.dto.req.UserLoginReqDTO;
import com.weyoung.admin.dto.req.UserRegisterReqDTO;
import com.weyoung.admin.mapper.UserMapper;
import com.weyoung.admin.service.UserService;
import com.weyoung.common.consatant.exception.ClientException;
import com.weyoung.common.enums.UserErrorCodeEnum;
import com.weyoung.common.model.entity.UserDO;
import com.weyoung.common.utils.AES;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {


    @Override
    public Void login(UserLoginReqDTO requestParam) {
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, requestParam.getUsername());
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        if (userDO == null) {
            throw new ClientException(UserErrorCodeEnum.USER_NULL);
        }
        if (!userDO.getPassword().equals(AES.encrypt(requestParam.getPassword()))) {
            throw new ClientException(UserErrorCodeEnum.USER_PASSWORD_ERROR);
        }
        StpUtil.login(userDO.getUserId());
        return null;
    }

    @Override
    public Void register(UserRegisterReqDTO requestParam) {
        int insert = baseMapper.insert(BeanUtil.toBean(requestParam, UserDO.class));
        if (insert < 1) {
            throw new ClientException(UserErrorCodeEnum.USER_SAVE_ERROR);
        }
        return null;
    }
}
 